package net.itheima.mm.controller;

import lombok.extern.slf4j.Slf4j;
import net.itheima.mm.entity.PageResult;
import net.itheima.mm.entity.QueryPageBean;
import net.itheima.mm.entity.Result;
import net.itheima.mm.exception.CustomException;
import net.itheima.mm.pojo.Catalog;
import net.itheima.mm.pojo.Course;
import net.itheima.mm.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author zhangyan
 * @date 2021/2/25 19:52
 */

@RestController
@RequestMapping("/course")
@Slf4j
public class CourseController {

    @Autowired
    CourseService courseService;

    //分页查询 学科
    @RequestMapping("/findListByPage")
    public Result findListByPage(@RequestBody QueryPageBean queryPageBean){

        PageResult pageResult = new PageResult();

        log.debug("findListByPage:" + queryPageBean);
        List<Course> list = courseService.findListByPage(queryPageBean);

        long total = courseService.getTotal();

        pageResult.setTotal(total);
        pageResult.setRows(list);

        return new Result(true,"学科查询成功",pageResult);
    }

    @RequestMapping("/add")
    public Result add(@RequestBody Course course) {
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(date);
        course.setCreateDate(dateString);

        log.debug("add:" + course);
        courseService.add(course);
        log.info("添加成功");
        return new Result(true, "添加成功!");
    }

    @RequestMapping("/update")
    public Result update(@RequestBody Course course){
        courseService.update(course);
        return new Result(true,"修改成功!");
    }

    @RequestMapping("/delete")
    public Result delete(@RequestParam("courseId") Integer id) {

        try {
            courseService.delete(id);
        }catch (Exception e){
            return new Result(false, "该学科下存在内容,不能删除!");
        }
        return new Result(true, "删除成功!");
    }
}
